package com;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.servlet.http.*;

import com.model.ChannelClient;
import com.model.PMF;

@SuppressWarnings("serial")
public class CleanClientIdsServlet extends HttpServlet {
  public static final int MINUTE = 3600;
  public static final int MILLI = 1000;

  private static final Logger log = Logger.getLogger(CleanClientIdsServlet.class.getName());

  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    resp.setContentType("text/html");
    resp.getWriter().println("Cleaning Clients...");

    
    // Get all channel client ids available
    String query = "select from " + ChannelClient.class.getName();
    PersistenceManager pm = PMF.get().getPersistenceManager();
    List<ChannelClient> ids = (List<ChannelClient>) pm.newQuery(query).execute();

    // Delete any clientids with timestamps older than an hour
    Date oneHourAgo = new Date();
    oneHourAgo.setTime(oneHourAgo.getTime() - MINUTE * MILLI);
    
    for (ChannelClient c : ids) {
      Date clientDate = c.getTimestamp();
      
      // if client timestamp is older than 1 hour, delete it.
      if (c.getTimestamp().before(oneHourAgo)){
        // Delete this client
        log.info("deleting stale client: " + c.getClientId());
        pm.deletePersistent(c);
      }
    }
  }


}
